package ee.propaganda.gparrot.client.presenter;

import java.util.HashMap;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.user.client.rpc.AsyncCallback;
import ee.propaganda.gparrot.client.app.AppServices;
import ee.propaganda.gparrot.client.event.ServicesDataUpdatedEventHandler;
import ee.propaganda.gparrot.client.model.Data;
import ee.propaganda.gparrot.client.model.ServiceInfo.ServiceType;
import ee.propaganda.gparrot.client.view.MainView;


public class ServicesPresenter implements Presenter, ServicesDataUpdatedEventHandler{
	private AppServices appServices;
	private final Display display;
	private final Data data;
	
	
	public ServicesPresenter(AppServices appServices){
		this.appServices = appServices;
		display = new MainView();
		display.setHeader(appServices.getLoginInfo().getLogoutUrl(), appServices.getLoginInfo().getEmailAddress());
		data = Data.getInstance();		
	}
	
	//show data on display
	public void updateDisplay(){
		display.setData(data.getServicesData());
		bind();
	}
	
	
	
	
	
	//-------------------------------------------
	//Helper methods
	
	//add handlers for UI events
	private void bind(){
		//add handler for register button(s)
		//TODO TEST: does the final keyword work here as expected with multiple services
		
		for (final ServiceType serviceType : ServiceType.values()) {
			if(!data.isRegistered(serviceType))
				display.getRegisterButton(serviceType).addClickHandler(new ClickHandler(){
	
					@Override
					public void onClick(ClickEvent event) {
						registerService(serviceType);
						
					}
				});
		}
		
		
	}
	
	//get authorized token for service access and persist it; update 
	private void registerService(final ServiceType st) {
	
		appServices.getAuthService().getAccess(appServices.getLoginInfo(), st, new AsyncCallback<String>() {

			@Override
			public void onFailure(Throwable caught) {
				appServices.handleError(caught);							
			}

			@Override
			public void onSuccess(String result) {
				data.update(st, result);
			}
			
		});
	}

	
	
	
	
	//Display interface
	public interface Display {
	    
		void setHeader(String logOutUrl, String email);
		HasClickHandlers getRegisterButton(ServiceType st);
	    void setData(HashMap<ServiceType, Boolean> simpleData);
	}





	@Override
	public void onDataUpdated() {
		updateDisplay();
	}

}
